import os.path
import cv2
import numpy as np
import argparse
from collections import OrderedDict
import streamlit as st
from source.proprecess import *
from source.utils import (
    select_transforms, load_transforms_config, transform2func, get_images)


def main():

    st.set_page_config(
        page_title="CVStudio App",
        page_icon="📊",
        layout="wide",
        initial_sidebar_state="expanded",
        menu_items={
            'Get Help': 'https://www.extremelycoolapp.com/help',
            'Report a bug': "https://www.extremelycoolapp.com/bug",
            'About': "# This is a header. This is an *extremely* cool app!"
        }
    )

    # execute_mode = st.sidebar.toggle("**启动连续变换**")
    with st.sidebar.expander("**执行模式**", expanded=True):
        execute_mode = st.radio(
            "**执行模式**",
            ["单个变换", "连续变换"],
            index=None, label_visibility='collapsed', horizontal=True
        )

    # st.sidebar.divider()
    uploaded_files = st.sidebar.file_uploader('**选择文件:**',
                                              accept_multiple_files=True,
                                              label_visibility='collapsed',
                                              type=['png', 'jpg', 'jpeg', 'bmp', 'tif'],
                                              help="'png', 'jpg'")

    if len(uploaded_files) == 0:
        st.title("Please upload the image.")
        # image_files = get_images('./images')
        # image_files = sorted(image_files, key=os.path.basename)
        # images = [cv2.imdecode(np.fromfile(f, dtype=np.uint8), 1)
        #           for f in image_files]
    # else:

    images = []
    for uploaded_file in uploaded_files:
        image = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1)
        # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        images.append(image)

    st.sidebar.divider()

    transforms = load_transforms_config('./config.yml')

    transform_names = select_transforms(transforms, execute_mode)

    for image_id, image in enumerate(images, start=1):
        function_name = transform2func(transform_names[0][0])
        image_transformed = function_name(image, **transform_names[0][1])

        images = OrderedDict({"**原始图像**": image})

        for step, (transform_name, transform_args) in enumerate(transform_names, start=1):
            function_name = transform2func(transform_name)
            image_transformed = function_name(image_transformed, **transform_args)
            images.update({f"**步骤{str(step)}**: **{transform_name}**": image_transformed.copy()})

        cols = st.columns(len(images), gap='small')
        for col, (key, value) in zip(cols, images.items()):
            with col:
                st.markdown(key)
                if len(value.shape) == 3:
                    st.image(value, channels='BGR')
                else:
                    st.image(value)

        # col1, col2 = st.columns(2, gap='small')
        # with col1:
        #     st.markdown('**原始图像**')
        #     if len(image.shape) == 3:
        #         st.image(image, channels='BGR')
        #     else:
        #         st.image(image)
        # with col2:
        #     st.markdown('**结果图像**')
        #     if len(image_tranformed.shape) == 3:
        #         st.image(image_tranformed, channels='BGR')
        #     else:
        #         st.image(image_tranformed)

        st.divider()

    # st.markdown("<font face='黑体' size=5>黑体字</font>", unsafe_allow_html=True)
    st.spinner()


if __name__ == '__main__':
    main()